package com.frontop.config;

import com.frontop.common.domain.UserJurisdiction;
import com.frontop.modules.mapper.TUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author YangBoos
 * @title: JwtTokenEnhancer
 * @projectName frontop-cloud
 * @description: JWT的增强器，可在tokent中添加额外内容
 */
@Component
public class JwtTokenEnhancer implements TokenEnhancer {
    @Autowired
    TUserMapper tUserMapper;

    /**
     * 增加token中的扩展信息
     * @param oAuth2AccessToken
     * @param oAuth2Authentication
     * @return
     */
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        User user = (User)oAuth2Authentication.getUserAuthentication().getPrincipal();
        String userName = user.getUsername();
        UserJurisdiction userJurisdiction = tUserMapper.getUserJurisdictionByUserName(userName);
        Map<String, Object> info = new HashMap<>();
        info.put("jwt-userJurisdiction", userJurisdiction);
        ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(info);
        return oAuth2AccessToken;
    }

}